/*
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-09-25 18:27:11
 * @LastEditTime: 2019-11-05 10:32:59
 * @LastEditors: Please set LastEditors
 */
import { constantRoutes } from '@/router'
import api from '@/api/api'
import Layout from '@/layout'
// import { resetRouter } from '../../router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      var routerAdd = []
      let accessedRoutes = []
      api.get_powers([]).then(res => {
        for (let i = 0; i < res.data.length; i++) {
          routerAdd[i] = []
          routerAdd[i] = {
            path: '/' + res.data[i].path,
            component: Layout,
            name: res.data[i].path,
            meta: {
              title: res.data[i].name,
              icon: res.data[i].icon
            },
            children: []
          }
          if (res.data[i].children) {
            for (let j = 0; j < res.data[i].children.length; j++) {
              routerAdd[i].children.push(
                {
                  path: '/' + res.data[i].path + '/' + res.data[i].children[j].path,
                  component: () => import(`@/views/${res.data[i].path}/${res.data[i].children[j].path}`),
                  name: res.data[i].path + '-' + res.data[i].children[j].path,
                  hidden: res.data[i].children[j].hidden === '1',
                  meta: {
                    title: res.data[i].children[j].name
                  }
                }
              )
            }
          }
        }
        routerAdd.push({ path: '*', redirect: '/404', hidden: true })
        // if (roles.includes('admin')) {
        //   accessedRoutes = asyncRoutes || []
        // } else {
        accessedRoutes = filterAsyncRoutes(routerAdd, roles)
        // }
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
